<template>
  <PageWrapper title="审批记录" contentFullHeight fixedHeight>
    <template #tags>
      <Tag :color="currentStatus?.color">{{ currentStatus?.label }}</Tag>
    </template>
    <Card
      class="w-full h-full"
      :loading
      :tab-list="tabList"
      :active-tab-key="activeTabKey"
      @tab-change="(key) => (activeTabKey = key)"
    >
      <template #tabBarExtraContent>
        <a-button @click="handleClose">关闭页面</a-button>
      </template>
      <template #default>
        <Timeline
          v-if="historyRecordList.length && activeTabKey === 'tab1'"
          class="pt-8px h-[calc(100vh-300px)] overflow-y-scroll px-16px"
        >
          <TimelineItem v-for="item in historyRecordList" :key="item.id" color="blue">
            <div class="flex flex-row mb-3">
              <!-- 节点名称 -->
              <span class="font-bold">{{ item.name }}</span>
            </div>
            <div class="flex flex-row justify-between">
              <div id="left" class="flex gap-2 items-center">
                <Avatar :size="40" style="background-color: #fde3cf; color: #f56a00">{{
                  nameFormat(item.nickName)
                }}</Avatar>
                <div class="flex flex-col gap-5px">
                  <span>{{ item.nickName }}</span>
                  <div>
                    <Tag :color="transformColor(item)?.color">{{ item.statusName }}</Tag>
                  </div>
                </div>
              </div>
              <div id="right">
                <div class="text-gray-500" v-if="item.endTime">完成: {{ item.endTime }}</div>
                <div class="text-gray-500" v-if="item.runDuration"
                  >耗时: {{ item.runDuration }}</div
                >
              </div>
            </div>
            <!-- 评论 -->
            <div class="py-5px" v-if="item.comment">
              <Alert :message="item.comment" type="info" />
            </div>
            <!-- 附件 contentId为oss下载id  -->
            <div v-if="item.attachmentList" class="flex flex-row items-center">
              <div>附件: </div>
              <a-button
                type="link"
                v-for="file in item.attachmentList"
                :key="file.id"
                @click="handleDownload(file)"
                >{{ file.name }}</a-button
              >
            </div>
            <!-- 底部留一点间距 -->
            <div class="mb-2"></div>
          </TimelineItem>
        </Timeline>

        <div v-if="activeTabKey === 'tab2'">
          <BpmnViewer :instanceId="currentId" />
        </div>
      </template>
    </Card>
  </PageWrapper>
</template>

<script setup lang="ts">
  // 审批记录 页面
  import { PageWrapper } from '@/components/Page';
  import { useRoute } from 'vue-router';
  import { getHistoryRecord } from '@/api/workflow/processInstance';
  import type { HistoryRecordList } from '@/api/workflow/processInstance/model';
  import { computed, onMounted, ref } from 'vue';
  import { Card, Timeline, TimelineItem, Avatar, Alert, Tag } from 'ant-design-vue';
  import { downloadByData } from '@/utils/file/download';
  import { ossDownload } from '@/api/system/oss';
  import { useLoading } from '@/components/Loading';
  import { nodeStatusOptions } from '@/views/workflow/common';
  import { BpmnViewer } from '@/components/BpmnViewer';
  import { useTabs } from '@/hooks/web/useTabs';

  const route = useRoute();
  const currentId = (route.params.id as string) || '0';

  const tabList = [
    {
      key: 'tab1',
      tab: '审批记录',
    },
    {
      key: 'tab2',
      tab: '流程图',
    },
  ];
  const activeTabKey = ref<string>('tab1');
  const loading = ref<boolean>(true);

  /** 时间轴data */
  const historyRecordList = ref<HistoryRecordList[]>([]);
  onMounted(async () => {
    const records = await getHistoryRecord(currentId);
    historyRecordList.value = records.historyRecordList;

    loading.value = false;
  });

  const currentStatus = computed(() => {
    if (!historyRecordList.value.length) {
      return { label: '未知', value: 'unknown', color: 'default' };
    }
    const node = historyRecordList.value[0];
    const nodeStatus = nodeStatusOptions.find((item) => item.value === node.status);
    return nodeStatus;
  });

  function transformColor(list: HistoryRecordList) {
    return nodeStatusOptions.find((item) => item.value === list.status);
  }

  function nameFormat(name: string) {
    if (!name) return '';
    if (name.length <= 2) return name;
    // 保留最后两个
    return name.substring(name.length - 2);
  }

  const [openFullLoading, closeFullLoading] = useLoading({
    tip: '下载文件中...',
  });
  async function handleDownload(file: Recordable) {
    try {
      openFullLoading();
      const data = await ossDownload(file.contentId);
      downloadByData(data, file.name);
    } finally {
      closeFullLoading();
    }
  }

  const { closeCurrent } = useTabs();
  async function handleClose() {
    await closeCurrent();
  }
</script>

<style scoped></style>
